package com.sjx.app.base.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;

import com.sjx.app.base.BaseApplication;
import com.sjx.app.base.model.SkipAData;
import com.sjx.app.base.viewmodel.MvvmBaseViewModel;

public abstract class MvvmActivity<V extends ViewDataBinding, VM extends MvvmBaseViewModel> extends AppCompatActivity implements Observer {
    protected Activity mActivity;
    protected V viewDataBinding;
    protected VM viewModel;
    private Dialog loadingDialog;
    protected int requestFailureCount = 0;

    protected abstract @LayoutRes
    int getLayoutId();

    protected abstract VM getViewModel();

    public abstract int getBindingVariable();

    public abstract void onRetryBtnClick();

    protected String getActivityTag() {
        return this.getClass().getSimpleName();
    }

    /**
     * 初始化参数
     */
    protected void initParameters() {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        BaseApplication.addActivity(this);
        initParameters();
        viewDataBinding = DataBindingUtil.setContentView(this, getLayoutId());
        viewModel = getViewModel();
        getLifecycle().addObserver(viewModel);
        viewModel.viewStatusLiveData.observe(this, this);
        viewModel.errorMessage.observe(this, this);
        viewModel.loadingDialogLiveData.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    showLoadingDialog();
                } else {
                    hideLoadingDialog();
                }
            }
        });
        viewModel.skipActivityLiveData.observe(this, new Observer<SkipAData>() {
            @Override
            public void onChanged(SkipAData data) {
                skipActivity(data);
            }
        });
        initLifecycleAddObserver();
        if (getBindingVariable() > 0) {
            viewDataBinding.setVariable(getBindingVariable(), viewModel);
            viewDataBinding.executePendingBindings();
        }
        init();
    }

    protected abstract void initLifecycleAddObserver();

    protected abstract void init();

    protected abstract void skipActivity(SkipAData data);

    @Override
    public void onStart() {
        super.onStart();
        Log.d(getActivityTag(), "Activity:" + this + ": " + "onStop");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(getActivityTag(), "Activity:" + this + ": " + "onStop");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(getActivityTag(), "Activity:" + this + ": " + "onPause");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(getActivityTag(), "Activity:" + this + ": " + "onResume");
    }

    @Override
    public void onDestroy() {
        BaseApplication.removeActivity(this);
        super.onDestroy();
        Log.d(getActivityTag(), "Activity:" + this + ": " + "onDestroy");
    }

    /**
     * 创建LodingDialog
     */
    protected void createLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new ProgressDialog(this);
            loadingDialog.setCancelable(false);      //弹出后会点击屏幕或物理返回键是否消失
            loadingDialog.setCanceledOnTouchOutside(true);//弹出后会点击屏幕，dialog不消失；点击物理返回键dialog消失
        }
    }

    /**
     * 显示进度框
     */
    private void showLoadingDialog() {
        createLoadingDialog();
        if (!loadingDialog.isShowing())
            loadingDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void hideLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    /**
     * 权限检查
     *
     * @param neededPermissions 需要的权限
     * @return 是否全部被允许
     */
    protected boolean checkPermissions(String[] neededPermissions) {
        if (neededPermissions == null || neededPermissions.length == 0) {
            return true;
        }
        boolean allGranted = true;
        for (String neededPermission : neededPermissions) {
            allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED;
        }
        return allGranted;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean isAllGranted = true;
        for (int grantResult : grantResults) {
            isAllGranted &= (grantResult == PackageManager.PERMISSION_GRANTED);
        }
        if (viewModel != null) viewModel.isAllGrantedPermission = isAllGranted;
        afterRequestPermission(requestCode, isAllGranted);
    }

    /**
     * 请求权限的回调
     *
     * @param requestCode  请求码
     * @param isAllGranted 是否全部被同意
     */
    public void afterRequestPermission(int requestCode, boolean isAllGranted) {
    }
}
